package com.studynotes.dev.tech.aspect.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.studynotes.dev.tech.common.utils.DynamicDBUtil;
import com.studynotes.dev.tech.common.utils.SpringContextUtil;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Liu XiaoJun
 * @description: 重写抽象类，实现多数据源
 * @date 2025-11-07 16:52:35
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    public static Map<Object, Object> targetDataSources = new ConcurrentHashMap<>(10);

    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicContextHolder.peek();

    }

    public static void setDataSource(String dbLinkKey) throws Exception{
        if(!DynamicDataSource.targetDataSources.containsKey(dbLinkKey)){
            DruidDataSource dataSource = DynamicDBUtil.getDbSourceByDbLinkKey(dbLinkKey);
            DynamicDataSource.targetDataSources.put(dbLinkKey,dataSource);
        }
        //切换动态多数据源的dbLinkKey
        DynamicContextHolder.push(dbLinkKey);
        DynamicDataSource dynamicDataSource = SpringContextUtil.getBean("dynamicDataSource");
        //使得修改后的targetDataSources生效
        dynamicDataSource.afterPropertiesSet();
    }

}

